package com.ambitor.ipro.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.exceptions.ProException;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.TaobaoUtil;
import com.taobao.api.TaobaoObject;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.TaobaoResponse;

public class TopBatchClient {

	private TopClient topClient;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	public TopBatchClient() {
		topClient = new TopClient();
	}

	public TopBatchClient(boolean isRealEnv, String appkey, String appsecret) {
		topClient = new TopClient(isRealEnv, appkey, appsecret);
	}

	public long getCount(TaobaoRequest request, String userName)
			throws ProException {
		return getCount(request, null, userName);
	}

	public long getCount(TaobaoRequest request, String sessionId, String nick)
			throws ProException {
		logger.info(nick + "开始调用" + request.getApiMethodName());
		TaobaoUtil.setPageNo(request, 1);
		TaobaoUtil.setPageSize(request, 1);
		TaobaoResponse taobaoResponse = topClient.execute(request, sessionId,
				nick);
		try {
			return TaobaoUtil.getTotalResults(taobaoResponse);
		} catch (Exception e) {
			String desc = nick + "调用getTotalResults()过程中发生Exception";
			throw new ProException(ResultCode.EXCEPTION, desc, e);
		}
	}

	/**
	 * 最初代码写错了，要改的话代价太高，只好添加了这个2b方法委曲求全
	 * 
	 * @param request
	 * @param sessionId
	 * @param nick
	 * @return
	 */
	private TaobaoResponse getFuckedCount(TaobaoRequest request,
			String sessionId, String nick) throws ProException {
		TaobaoUtil.setPageNo(request, 1);
		TaobaoUtil.setPageSize(request, 1);
		return topClient.execute(request, sessionId, nick);
	}

	public <T extends TaobaoResponse> T batchExecute(TaobaoRequest request,
			Class<?> beanType, String userName) throws ProException {
		return batchExecute(request, beanType, null, userName);
	}

	@SuppressWarnings("unchecked")
	public <T extends TaobaoResponse> T batchExecute(TaobaoRequest request,
			Class<?> beanType, String sessionId, String nick)
			throws ProException {
		logger.info(nick + "开始调用" + request.getApiMethodName());
		TaobaoResponse taobaoResponse = getFuckedCount(request, sessionId, nick);
		long totalResults = 0;
		try {
			totalResults = TaobaoUtil.getTotalResults(taobaoResponse);
		} catch (Exception e) {
			String desc = nick + "调用getTotalResults()过程中发生Exception";
			throw new ProException(ResultCode.EXCEPTION, desc, e);
		}
		if (totalResults == 0) {
			return (T) taobaoResponse;
		}
		long totalPage = 1 + (totalResults - 1)
				/ Constants.TAOBAO_API_MAX_PAGE_SIZE;
		logger.info(nick + "共将请求" + totalResults + "条数据，按每页最多"
				+ Constants.TAOBAO_API_MAX_PAGE_SIZE + "条计算，计" + totalPage
				+ "页");

		int page = 1;
		TaobaoUtil.setPageSize(request, Constants.TAOBAO_API_MAX_PAGE_SIZE);
		List<TaobaoObject> totalTaobaoObjectList = new ArrayList<TaobaoObject>();

		while (page <= totalPage) {
			logger.info(nick + "开始请求第" + page + "页数据操作");
			TaobaoUtil.setPageNo(request, page);
			try {
				taobaoResponse = topClient.execute(request, sessionId, nick);
			} catch (ProException e) {
				String desc = nick + "在请求第" + page + "页数据时发生Exception";
				throw new ProException(ResultCode.EXCEPTION, desc, e);
			}
			Result result = TaobaoUtil.parseTaobaoApiResponse(taobaoResponse);
			if (result.getCode() < 0) {
				logger.warn(nick + "在请求第" + page + "页数据操作时失败,将立即返回.错误信息为"
						+ result.getMsg());
				return (T) taobaoResponse;
			}
			logger.info(nick + "成功请求第" + page + "页数据操作");
			List<TaobaoObject> TaobaoObjectList = TaobaoUtil
					.getInternalBeanList(taobaoResponse, beanType);
			logger.info(nick + "的第" + page + "次请求返回" + TaobaoObjectList.size()
					+ "条数据");
			if (TaobaoObjectList != null && TaobaoObjectList.size() > 0) {
				totalTaobaoObjectList.addAll(TaobaoObjectList);
				logger.info(nick + "第" + page + "次请求后totalTaobaoObjectList里累计有"
						+ totalTaobaoObjectList.size() + "条数据");
			}
			page++;
		}
		TaobaoUtil.fillResponseWithBeanList(taobaoResponse, beanType,
				totalTaobaoObjectList);
		logger.info(nick + "调用" + request.getApiMethodName() + "结束,共返回"
				+ totalTaobaoObjectList.size() + "条数据");
		return (T) taobaoResponse;
	}
}
